package org.aeon.gamechatnest.configuration.security;


import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.aeon.gamechatnest.common.Constant;
import org.aeon.gamechatnest.common.response.RespStatus;
import org.aeon.gamechatnest.common.response.ResultBuild;
import org.aeon.gamechatnest.dto.SecurityUserDto;
import org.aeon.gamechatnest.dto.UserCacheDto;
import org.aeon.gamechatnest.service.RoleService;
import org.aeon.gamechatnest.util.JsonUtil;
import org.aeon.gamechatnest.util.JwtUtil;
import org.aeon.gamechatnest.util.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

@Profile("sec")
@Component("jwtFilter")
public class JwtFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader(HttpHeaders.AUTHORIZATION);

        if (!StringUtils.hasText(token)) {
            filterChain.doFilter(request, response);
            return;
        }

        String username = jwtUtil.getUserFromToken(token);
        UserCacheDto userCache = redisCache.getCacheObject2(Constant.USER_TOKEN_CACHE_PREFIX + username);
        if (Objects.nonNull(userCache)) {
            SecurityUserDto securityUser = new SecurityUserDto();
            securityUser.setUserCache(userCache);

            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(securityUser, null, securityUser.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            filterChain.doFilter(request, response);
        } else {
            response.setContentType("application/json;charset=UTF-8");
            ServletOutputStream out = response.getOutputStream();
            out.write(Objects.requireNonNull(JsonUtil.obj2String(ResultBuild.result().state(RespStatus.TOKEN_ERROR).build())).getBytes(StandardCharsets.UTF_8));
            out.flush();
            out.close();
        }
    }
}
